package com.zx.kitchen.index.common.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.EndlessListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshEndlessListView;
import com.zx.kitchen.index.R;
import com.zx.kitchen.index.common.adapter.BusinessCenterAdapter;
import com.zx.kitchen.index.common.entity.PurchaseData;
import com.zx.kitchen.index.common.entity.PurchaseDataList;
import com.zx.kitchen.index.common.mvp.presenter.IndexPresenter;
import com.zx.kitchen.index.common.mvp.presenter.PurchasePresenter;
import com.zx.kitchen.index.common.mvp.view.PurchaseView;
import com.zx.kitchen.index.common.utils.TimeUtil;
import com.zx.kitchen.index.common.utils.Toasts;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * Created by Administrator on 2017/3/2.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class BusinessCenterActivity extends Activity implements View.OnClickListener, PurchaseView {
    private ImageView toolbarLeft;
    private TextView toolbarTitle;

    private PullToRefreshEndlessListView pullToRefreshListView;
    private TextView tabBusiness;
    private TextView tabPurchase;
    private Button btnNew;
    private BusinessCenterAdapter adapter;
    private List<PurchaseDataList> mList = new ArrayList<>();
    private PurchasePresenter purchasePresenter;
    private IndexPresenter indexPresenter;
    private Context context;
    private Calendar calendar;// 用来装日期的
    private DatePickerDialog dialog;
    private EditText etStartTime;
    private EditText etEndTime;
    private String startTime = TimeUtil.getToday();
    private String endTime = TimeUtil.getToday();
    private int p = 1;//分页 最小为1
    private boolean isPurchase = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_business_center);
        initView();
        setListener();


    }

    private void initView() {
        View view = findViewById(R.id.titleBar);
        toolbarLeft = (ImageView) view.findViewById(R.id.toolbar_leftLin);
        toolbarTitle = (TextView) view.findViewById(R.id.toolbar_title);
        tabBusiness = (TextView) findViewById(R.id.tab_business);
        tabPurchase = (TextView) findViewById(R.id.tab_purchase);
        btnNew = (Button) findViewById(R.id.btn_new);
        pullToRefreshListView = (PullToRefreshEndlessListView) findViewById(R.id.pull_refresh_list);
        toolbarTitle.setTextColor(getResources().getColor(R.color.blue));
        toolbarTitle.setText("营业中心信息");
        tabBusiness.setBackground(getResources().getDrawable(R.drawable.tab_bg_blue));

        //给pullToRefreshListView 加头
        AbsListView.LayoutParams layoutParams =
                new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        View headerView = getLayoutInflater().inflate(R.layout.header_select_date, pullToRefreshListView, false);
        headerView.setLayoutParams(layoutParams);
        ListView lv = pullToRefreshListView.getRefreshableView();
        lv.addHeaderView(headerView);
        etStartTime = (EditText) headerView.findViewById(R.id.et_start_time);
        etEndTime = (EditText) headerView.findViewById(R.id.et_end_time);
        purchasePresenter = new PurchasePresenter(this, context);
        indexPresenter = new IndexPresenter(this, context);
        adapter = new BusinessCenterAdapter(this, mList);
        pullToRefreshListView.setAdapter(adapter);

        etStartTime.setText(TimeUtil.getToday());
        etEndTime.setText(TimeUtil.getToday());

    }


    private void setListener() {
        toolbarLeft.setOnClickListener(this);
        tabBusiness.setOnClickListener(this);
        tabPurchase.setOnClickListener(this);
        btnNew.setOnClickListener(this);
        toolbarTitle.setOnClickListener(this);

        etStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                calendar = Calendar.getInstance();
                dialog = new DatePickerDialog(BusinessCenterActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String mm = "";
                        String dd = "";
                        if ((monthOfYear + 1) < 10) {
                            mm = "0" + (monthOfYear + 1);
                        } else {
                            mm = (monthOfYear + 1) + "";
                        }
                        if (dayOfMonth < 10) {
                            dd = "0" + dayOfMonth;
                        } else {
                            dd = "" + dayOfMonth;
                        }
                        startTime = year + "-" + mm + "-" + dd;
                        Log.d("BusinessCenterActivity", "compareDate(startTime,endTime):" + compareDate(startTime, endTime));
                        if (compareDate(startTime, endTime) > 0) {
                            Toasts.show(context, "开始时间不能大于结束时间");
                            return;
                        }
                        etStartTime.setText(year + "-" + mm + "-" + dd);
                    }
                }, calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH), calendar
                        .get(Calendar.DAY_OF_MONTH));
                dialog.show();
            }
        });
        etEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar = Calendar.getInstance();
                dialog = new DatePickerDialog(BusinessCenterActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String mm = "";
                        String dd = "";
                        if ((monthOfYear + 1) < 10) {
                            mm = "0" + (monthOfYear + 1);
                        } else {
                            mm = (monthOfYear + 1) + "";
                        }
                        if (dayOfMonth < 10) {
                            dd = "0" + dayOfMonth;
                        } else {
                            dd = "" + dayOfMonth;
                        }
                        endTime = year + "-" + mm + "-" + dd;
                        Log.d("BusinessCenterActivity", "compareDate(startTime,endTime):" + compareDate(startTime, endTime));
                        if (compareDate(startTime, endTime) > 0) {
                            Toasts.show(context, "开始时间不能大于结束时间");
                            return;
                        }
                        etEndTime.setText(year + "-" + mm + "-" + dd);
                    }
                }, calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH), calendar
                        .get(Calendar.DAY_OF_MONTH));
                dialog.show();

            }
        });
        pullToRefreshListView.getRefreshableView().setLoadingListener(new EndlessListView.PullLoadingListViewListener() {

            @Override
            public void onLoading() {
                mLoadMore();
            }
        });
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<EndlessListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<EndlessListView> refreshView) {
                String label = DateUtils.formatDateTime(getApplicationContext(),
                        System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                pullToRefreshListView.getRefreshableView().resetAllLoadingComplete();
                mRefreshData();
            }
        });
    }

    private void mRefreshData() {
        onLoadData(true, isPurchase);
    }

    private void mLoadMore() {
        onLoadData(false, isPurchase);
    }

    private void onLoadData(boolean isRefresh, boolean isPurchase) {
        if (isRefresh) {
            p = 1;
        } else {
            p++;
        }
        if (isPurchase) {
            purchasePresenter.getFromNet(p, startTime, endTime);
        } else {
            indexPresenter.getFromNet(p, startTime, endTime);
        }
    }

    public void openCalendar(final EditText editText) {
        calendar = Calendar.getInstance();
        dialog = new DatePickerDialog(BusinessCenterActivity.this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String mm = "";
                String dd = "";
                if ((monthOfYear + 1) < 10) {
                    mm = "0" + (monthOfYear + 1);
                } else {
                    mm = (monthOfYear + 1) + "";
                }
                if (dayOfMonth < 10) {
                    dd = "0" + dayOfMonth;
                } else {
                    dd = "" + dayOfMonth;
                }
                editText.setText(year + "-" + mm + "-" + dd);
            }
        }, calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    public static int compareDate(String DATE1, String DATE2) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime1 = null;
        try {
            dateTime1 = dateFormat.parse(DATE1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date dateTime2 = null;
        try {
            dateTime2 = dateFormat.parse(DATE2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = dateTime1.compareTo(dateTime2);
        /**
         * 如果参数 Date 等于此 Date，则返回值 0；
         * 如果此 Date 在 Date 参数之前，则返回小于 0 的值；
         * 如果此 Date 在 Date 参数之后，则返回大于 0 的值。
         */
        return i;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_leftLin:
                finish();
                break;
            case R.id.tab_business:
                isPurchase = false;
                toolbarTitle.setText("营业中心信息");
                tabBusiness.setBackground(getResources().getDrawable(R.drawable.tab_bg_blue));
                tabPurchase.setBackgroundColor(getResources().getColor(R.color.white));
                onLoadData(false, isPurchase);
                adapter.notifyDataSetChanged();
                btnNew.setText("新建营业信息");
                break;
            case R.id.tab_purchase:
                isPurchase = true;
                toolbarTitle.setText("采购中心信息");
                tabPurchase.setBackground(getResources().getDrawable(R.drawable.tab_bg_blue));
                tabBusiness.setBackgroundColor(getResources().getColor(R.color.white));
                onLoadData(false, isPurchase);
                adapter.notifyDataSetChanged();
                btnNew.setText("新建采购信息");
                break;
            case R.id.btn_new:
                startActivity(new Intent(this, NewBusinessInfoActivity.class).putExtra("type",isPurchase));
                break;
            case R.id.toolbar_title:
                startActivity(new Intent(this, IndexActivity.class));
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        onLoadData(false, isPurchase);
    }

    @Override
    public void onSuccess(PurchaseData data) {
        pullToRefreshListView.onRefreshComplete();
        pullToRefreshListView.getRefreshableView().loadingCompleted();
        mList.clear();
        if (data.getList() != null) {
            mList.addAll(data.getList());
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFail(String str) {
        pullToRefreshListView.getRefreshableView().loadingCompleted();
        pullToRefreshListView.onRefreshComplete();
    }
}
